package qmm.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import qmm.dao.CartDao;
import qmm.entity.vo.CartVo;
import qmm.util.jdbcutil;
public class CarDaoImpl {
	public int add(int goodsId, int num, int userId) {
		String sql = "insert into t_cart values(null,"+goodsId+","+num+","+userId+")";
		return JdbcUtil.update(sql);
	}

	@Override
	public int getCount(int userId) {
		int n = 0;
		String sql = "select count(*) from t_cart where user_id="+userId;
		Connection conn = JdbcUtil.getConnection();
		Statement st;
		try {
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			if(rs.next()){
				n = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return n;
	}

	@Override
	public List<CartVo> findCartVo(int userId) {
		List<CartVo> list = new ArrayList<CartVo>();
		String sql = "select c.id,c.goods_id,g.goods_name,g.file_name,g.price,c.num from t_cart c inner join t_goods g on c.goods_id=g.id where c.user_id="+userId;
		Connection conn = JdbcUtil.getConnection();
		Statement st;
		try {
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			while(rs.next()){
				int id = rs.getInt("id");
				int goodsId = rs.getInt("goods_id");
				String goodsName = rs.getString("goods_name");
				double price = rs.getDouble("price");
				int num = rs.getInt("num");
				String fileName = rs.getString("file_name");
				CartVo vo = new CartVo(id,goodsId, goodsName, fileName, price, num);
				list.add(vo);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public int updateNum(int goodsId, int num, int userId) {
		String sql="update t_cart set num = num+"+num+" where goods_id="+goodsId+" and user_id="+userId;
		return JdbcUtil.update(sql);
	}

	@Override
	public int getGoodsId(int goodsId, int userId) {
		int n = 0;
		String sql = "select count(*) from t_cart where goods_id="+goodsId+" and  user_id="+userId;
		Connection conn = JdbcUtil.getConnection();
		Statement st;
		try {
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			if(rs.next()){
				n = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return n;
	}

	@Override
	public int getNum(int userId) {
		int n = 0;
		String sql = "select sum(num) from t_cart where user_id="+userId;
		Connection conn = JdbcUtil.getConnection();
		Statement st;
		try {
			st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			if(rs.next()){
				n = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return n;
	}

	@Override
	public int updateNum(int id, int num) {
		String sql="update t_cart set num = "+num+" where id="+id;
		return jdbcutil.update(sql);
	}
	public int del(int id) {
		String sql="delete from t_cart where id="+id;
		return JdbcUtil.update(sql);
	}

}
